<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use app\common\model\UserRelease as UserReleaseModel;
use think\facade\Cache;
use think\facade\Event;

class User extends Base
{

    protected $name = 'user';

    protected $type = [
        'active_time' => 'timestamp',
        'real_time' => 'timestamp',
    ];

    public function assets()
    {
        return $this->hasOne(Assets::class, 'uid');
    }

    public function getPhotoAttr($value)
    {
        return $value ?: Cache::get('system')['default_photo'];
    }
    public static function _save($param, $logs)
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $original = self::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    return ['code' => -1, 'msg' => '记录不存在，请检查！'];
                }
                $logs['original'] = $original;
                $oldUser = parent::where('id', $param['id'])->find();
                if ($oldUser->parent_code != $param['parent_code']) {
                    $parent = parent::where('code', $param['parent_code'])->find();
                    Relation::Referrer($param['id'], $parent->id);
                }
                $model = self::update($param);
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                $count = parent::where(['mobile' => $param['mobile']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '手机号已被注册'];
                }
                $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $param['code'] = trim($param['mobile']);
                $param['mobile'] = trim($param['mobile']);
                $param['parent_id'] = $parent->id;
                $param['parent_name'] = $parent->nickname;
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('111111');
                $param['pay_password'] = !empty($param['pay_password']) ? md5($param['pay_password']) : md5('222222');
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功', 'url' => url('login/index')->build()];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //微信小程授权登录
    public static function _miniAppletSave($param)
    {
        try {
            if (!isset($param['openid'])) {
                return ['code' => -1, 'msg' => '无效code'];
            }
            $info = parent::where('openid', $param['openid'])->find();
            $token = md5(json_encode($param) . $param['openid'] . time());
            if ($info) {
                if(empty($info->wx_openid)){
                    $info->wx_openid = $param['wx_openid'];
                }
                $info->last_time = time();
                $info->last_ip = request()->ip();
                $info->token = $token;
                $info->save();
            } else {
                $code = generate(6, '', 1);
                $update['nickname'] = '';
                $update['photo'] = '';
                $update['openid'] = $param['openid'];
                $update['wx_openid'] = $param['wx_openid'];
                $update['last_time'] = time();
                $update['last_ip'] = request()->ip();
                $update['token'] = $token;
                $update['code'] = $code;
                $update['is_active'] = 2;
                $update['active_time'] = time();
                $parent = parent::where(['id' => 1, 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $update['parent_id'] = $parent->id;
                $update['parent_code'] = $parent->code;
                $update['parent_name'] = $parent->nickname;
                parent::create($update);
            }
            return ['code' => 1, 'msg' => '登录成功', 'result' => ['token' => $token]];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _miniAppletEdit($param, $user)
    {
        parent::startTrans();
        try {

            if (isset($param['nickname']) && $param['nickname']) {
                $user->nickname = $param['nickname'];
            }

            if (isset($param['photo']) && $param['photo']) {
                $user->photo = $param['photo'];
            }
            if (isset($param['mobile']) && $param['mobile']) {
                if (!$user->mobile) {
                    $user->mobile = $param['mobile'];
                }
            }

            $user->save();
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function onAfterInsert($user)
    {

        if ($user->parent_code) {
            Relation::generate($user->id, $user->code, $user->parent_id, $user->parent_code);
        }
        $user->assets()->save(['uid' => $user->id]);
    }


    public static function recharge($param, $admin)
    {
        try {
            parent::startTrans();
            try {
                $user = parent::find($param['id']);
                if ($user->isEmpty()) {
                    return json(['code' => -1, 'msg' => '未查询到相关会员']);
                }
                $account = get_pay_way($param['account']);
                if ($param['mode'] == 1) {
                    Target::Account()
                        ->basics($param['id'], $param['account'], $param['amount'], '后台充值', '+')
                        ->setMsg($param['remarks'])
                        ->createRecharge();
                    $logs = '后台充值【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
                } else {
                    Target::Account()
                        ->basics($param['id'], $param['account'], $param['amount'], '后台扣除', '-')
                        ->setMsg($param['remarks'])
                        ->createRecharge();
                    $logs = '后台扣除【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
                }

                Logs::adds($logs, $admin['id'], $admin['admin_name']);

                parent::commit();
                return json(['code' => 1, 'msg' => '操作成功']);

            } catch (\Exception $e) {
                parent::rollback();
                return json(['code' => -1, 'msg' => $e->getMessage()]);
            }


        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
    public static function geMinTeam($uid)
    {
        $areaData = parent::where('parent_id', $uid)->order('team_total', 'desc')->column('my_total+team_total as team_total');
        if ($areaData) {
            array_shift($areaData);
            if (!empty($areaData)) return array_sum($areaData);
        }
        return 0;
    }

}
